import { FakeApi } from '@wowon/utils';
import { getCurrentUser } from '../../auth-center';

export const userSetting = new FakeApi([], {
  queryType: { userid: 'is' },
  sort: () => 0,
});

export default {
  /** 保存用户设置 */
  'POST /mock/setting/update': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    const userid = currentUser.data.id;
    const setting = userSetting.getItem({ userid });

    // 查询不到就创建，否则更新数据
    const operation = !setting ? 'create' : 'update';
    const data = { ...req.body, userid };
    if (!!setting) data.id = setting.id;
    const result = await userSetting[operation](data);
    res.json({ ...result, message: !result.success ? '更新失败' : '更新成功！' });
  },
  /** 获取用户设置 */
  'GET /mock/setting/get': async (req, res) => {
    const currentUser = getCurrentUser(req);
    if (!currentUser) {
      res.statusCode = 401;
      res.json({ code: '-1', message: '权限不足' });
      return;
    }
    const userid = currentUser.data.id;
    const result = await userSetting.profile({ userid });
    if (!result.success) {
      // 如果查询不到，直接返回 null，表示用户没有初始设置
      res.json({ code: '0', data: null, message: '成功！' });
      return;
    }
    res.json(result);
  },
};
